import {
  Button, Form, Input, Space, Typography
} from 'antd';
import Axios from 'axios';
import { useRequest, useUnmount, useKeyPress } from 'ahooks';
import { useHistory } from 'react-router-dom';
import md5 from 'md5';

import * as APIS from '../../../constants/api-constants';
import './style.less';

const { Paragraph } = Typography;

const Login = () => {
  const [form] = Form.useForm();
  const history = useHistory();
  const { loading, run, cancel } = useRequest((data) => {
    const { name, password } = data;
    return {
      url: APIS.AUTHORIZATION,
      method: 'GET',
      params: {
        name,
        password: md5(password)
      }
    };
  }, {
    manual: true,
    onSuccess: (result) => {
      const { token } = result.data;

      if (token) {
        localStorage.setItem('Authorization', `Bearer ${token}`);
        Axios.defaults.headers.common.Authorization = `Bearer ${token}`;
        history.push('/home/answerSetting');
      }
    },
    onError: () => {}
  });

  useKeyPress('enter', () => {
    form.submit();
  });

  useUnmount(() => {
    cancel();
  });

  return (
    <div className="login">
      <div className="container">
        <div className="container_head">
          <div className="title">
            <Space>
              <span className="title_logo" />
              <span className="title_description">专业心理测评&nbsp;管理系统</span>
            </Space>
          </div>
          <Paragraph>
            <ul>
              <li>更方便做到测评</li>
              <li>更快速计算测评结果</li>
              <li>更便捷管理回答</li>
            </ul>
          </Paragraph>
        </div>
        <div className="container_body">
          <div className="inbody">
            <Form form={form} onFinish={(data) => run(data)}>
              <Form.Item
                name="name"
                rules={[{ message: '账号不能为空', required: true }]}
              >
                <Input placeholder="用户名..." size="large" />
              </Form.Item>
              <Form.Item
                name="password"
                rules={[{ message: '密码不能为空', required: true }]}
              >
                <Input
                  placeholder="密码..."
                  type="password"
                  size="large"
                />
              </Form.Item>
              <Form.Item>
                <Button
                  className="inbody_button"
                  type="primary"
                  loading={loading}
                  onClick={() => { form.submit(); }}
                >
                  登录网站
                </Button>
              </Form.Item>
            </Form>
          </div>
        </div>
      </div>
    </div>

  );
};

export default Login;
